package com.atguigu.flink.chapter11;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2022/10/31 10:41
 */
public class Flink04_TableApi_Kafka {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
       
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        // 通过表的执行直接从文件中读取数据
        Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
    
    
        tEnv
            .connect(
                new Kafka()  // kafka 的连接参数
                    .version("universal") // 通用关闭
                    .property("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092")
                    .property("group.id", "atguigu")
                    .topic("s1")
                    .startFromLatest()
            )
            .withFormat(new Json())
            .withSchema(schema)
            .createTemporaryTable("sensor");
    
        Table table = tEnv.from("sensor");
    
        Table result = table
            .where($("id").isEqual("sensor_1"))
            .select("*");
    
        // sink 表
        tEnv
            .connect(
                new Kafka()  // kafka 的连接参数
                    .version("universal") // 通用关闭
                    .property("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092")
                    .topic("s2")
                    .sinkPartitionerRoundRobin()
                   
            )
            .withFormat(new Json())
            .withSchema(schema)
            .createTemporaryTable("abc");
    
        result.executeInsert("abc");
        
    
    
    }
}
/*
TableApi

SQL

 */